package com.yrh.dao.impl;

import com.yrh.bean.TCategory;
import com.yrh.dao.TCategoryDao;
import com.yrh.utils.DataSourceUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/*餐品分类数据层接口实现类*/
public class TCategoryDaoImpl implements TCategoryDao {
    private JdbcTemplate temp=new JdbcTemplate(DataSourceUtil.getDataSource());
    //查询所有分类
    @Override
    public List<TCategory> allCategory() {
        return temp.query("select * from t_category",new BeanPropertyRowMapper<>(TCategory.class));
    }
    //查询餐品是否存在
    @Override
    public TCategory byName(String name) {
        try {
            return temp.queryForObject("select * from t_category where category_name=?",new BeanPropertyRowMapper<>(TCategory.class)
            ,name);
        } catch (Exception e) {
         return null;
        }
    }
    //修改菜品
    @Override
    public int updateCate(TCategory tCategory) {
        return temp.update("update t_category set category_name=? where category_id=?",tCategory.getCategoryName(),tCategory.getCategoryId());
    }
    //删除菜品
    @Override
    public int delCate(TCategory tCategory) {
        //查询该分类下是否存在该商品
        Integer num = temp.queryForObject("SELECT COUNT(*) FROM t_product WHERE category_id=?", Integer.class, tCategory.getCategoryId());
        if (num==0){//不存在可以删除
          return temp.update("delete from t_category where category_id=?",tCategory.getCategoryId());
        }
        //菜品表置空
        return 0;

    }
   //添加菜品
    @Override
    public int addCate(TCategory tCategory) {
        return temp.update("insert into t_category(category_name) values (?)",tCategory.getCategoryName());
    }
}
